﻿using System.Text.Json.Serialization;

namespace DimensionsHelper.Client.WinUi.Models;

public class PageInfo
{
    public string Id { get; set; } = string.Empty;
    public string Title { get; set; } = string.Empty;
    public string Description { get; set; } = string.Empty;
    public string GlyphCode { get; set; } = string.Empty;
    public string Character => char.ConvertFromUtf32(Convert.ToInt32(GlyphCode, 16));
    public PageInfo[] SubPages { get; set; } = [];
    public string FullTypeName => $"DimensionsHelper.Client.WinUi.ViewModels.{Id}ViewModel";
    public bool WithSeparator { get; set; } = false;
}

public class PageInfoData
{
    public PageInfo[] Data { get; set; } = [];
}

[JsonSourceGenerationOptions(PropertyNameCaseInsensitive = true, IgnoreReadOnlyProperties = true)]
[JsonSerializable(typeof(PageInfo))]
[JsonSerializable(typeof(PageInfoData))]
public partial class PageInfoSourceJsonContext : JsonSerializerContext
{
}

public class PageInfoDataSource
{
    private static readonly object Lock = new();
    private PageInfoData _data = new();


    private bool _isDataInitialized;

    public static PageInfoDataSource Instance { get; } = new();


    public PageInfo[] GetPageInfos() => _data.Data;


    public PageInfo[] GetPageInfosOfType(Type type) => _data.Data.First(e => e.FullTypeName == type.FullName).SubPages;


    public async Task InitPageInfoAsync()
    {
        lock (Lock)
        {
            if (_isDataInitialized)
            {
                return;
            }
        }

        string jsonText = await StorageHelper.LoadText("Models/PageInfoData.json");
        if (JsonSerializer.Deserialize(jsonText, typeof(PageInfoData), PageInfoSourceJsonContext.Default) is
            PageInfoData data)
        {
            _data = data;
        }

        _isDataInitialized = true;
    }
}